﻿using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WsProtocol.IEC62056;
using WsProtocol.PublicClass;
using Comm.PublicClass;
using System.Runtime.Serialization;
using Wasion.HHU.Data.Repositories;

namespace WsProtocol.IEC62056MDL
{
    //属性定义
    [DataContract]
    public class ProObAttr : ProICAttrMth
    {
        private static VObAttrMthDbRepository vObAttrMthDbRepository = new VObAttrMthDbRepository();
        private static string ptltable = "T_ObAttrMth";
        private string objid;
        private static DataTable dtAll = null;  //所有数据
        //new public static List<ProObAttr> Attrlst = new List<ProObAttr>();  //属性列表 
        public static Dictionary<string, ProObAttr> Attrlst = new Dictionary<string, ProObAttr>();  //属性列表
        public static Dictionary<string, ProObAttr> DefValueParlst = null; // = new Dictionary<string, ProObAttr>();  //推荐值参数列表

        #region 语言相关的字段
        public string BaseProName { get; set; }
        public string BaseUnits { get; set; }
        public string BaseDescs { get; set; }
        public string BaseDisplay { get; set; }
        #endregion

        public string OBIS { get; set; }      
        public string DefValue { get; set; } //默认值        
        public ProObject proObject{ get; set; }  //所属对象        
        public List<ProObAttr> EleLst { get; set; } //属性包含的元素列表
        new public ProObAttr  ParentAttr { get; set; }  //父属性

        public string tmpOption { get; set; }  //界面选择，针对CHOICE类型
        public string SpeParForm { get; set; }  //用于特殊参数输入窗口，比如事件记录参数输入
        public string nameForm { get; set; }  ////用于特殊参数输入窗口的参数名称，比如事件记录参数输入

        public string DataTypeInfo { get; set; }
        public List<ProObAttr> ParLst { get; set; } //参数列表,用于保存界面输入值        
        public string CAD { get; set; }  //类编号 + OBIS+属性序号+元素序号，中间都用'.'隔开       
        public List<string> AppendParStr; //特定的其他不参与组织命令但又需用到的附加参数,以逗号隔开,如软件比对
       
        public bool CanEdit { get; set; }  //是否可以通过外部字符串修改参数值，默认可以修改
        public string BackUP1 { get; set; }  //备用1
        public string BackUP2 { get; set; }  //备用2
        public string BackUP3 { get; set; }  //备用3

        public eleNodeType EleNodetype { get; set; }  //表示设置参数或抄读时是数据节点或附加参数节点,只用格式表示不了。
        public string ICAttrMthID { get; set; }  //hxh 所对应的接口类中属性或方法的ID,便于更新类属性或方法时能直接更新的对象里的相应项
        public string roleAuth { get; set; }  //hxh 2018-11-23对应的角色权限字符串

        public string RealValue { get; set; }  //shaunwang 2019-4-15 参数真实值，主要用于保存枚举类参数项的设定值
        public Dictionary<string, string> roleAuthDic = new Dictionary<string,string>();

        public List<ProObAttr> ReadParLst { get; set; } //抄读数据列表,与界面输入值分开存贮  
        public string ObjID
        {
            get
            {
                if (proObject != null)
                    return proObject.ID;
                else return objid;
            }
            set { objid = value; }
        }
        public List<ProObAttr> CaptureObjLst { get; set; }  //属性包含的捕捉对象列表
        
       
        public string ErrorInfo;  //错误信息
        public static List<string> FieldLst = new List<string>() { "ParentNode", "EleLst", "proObject", "ParentAttr", 
            "ParLst", "GetAfterSet", "GetDelay","ReadParLst","CaptureObjLst" };
        
        public ProObAttr()
        {
            BaseProName = string.Empty; 
            BaseUnits = string.Empty; 
            BaseDisplay = string.Empty; 
            BaseDescs = string.Empty;

            //proClass.ClassID = string.Empty;
            EleLst = new List<ProObAttr>();
            ParLst = new List<ProObAttr>();
            ReadParLst = new List<ProObAttr>();
            CaptureObjLst = new List<ProObAttr>();
            proObject = null;
            ParentAttr = null;
            checkState = CheckState.Unchecked;
            CAD = string.Empty;
            AppendParStr = new List<string>();
            CanEdit = true;
            EleNodetype = eleNodeType.Data;
            roleAuth = "01:03,16:03"; //默认这两个角色可读写
            DataType = enumData.Data.ToString();
            proClass = new ProIClass();
            Scaler = "0";
        }

        public ProObAttr(object AttrData) {
            try
            {
                EleLst = new List<ProObAttr>();
                ParLst = new List<ProObAttr>();
                ReadParLst = new List<ProObAttr>();
                CaptureObjLst = new List<ProObAttr>();
                AppendParStr = new List<string>();

                object[] DataArray = (object[])AttrData;
                ProName = DataArray[0].ToString();
                OBIS = DataArray[1].ToString();
                AttrMth = (AttrType)Enum.Parse(typeof(AttrType), DataArray[2].ToString()) ;
                Seq = int.Parse(DataArray[3].ToString());
                DataType = DataArray[4].ToString();
                DataLen = DataArray[5].ToString();
                Scaler = DataArray[6].ToString();
                Units = DataArray[7].ToString();

            }
            catch (Exception ex)
            {
            }
        
        }
        protected override void Dispose(bool disposing)
        {
            Attrlst.Remove(this.ID);
            if (proObject != null)
                proObject.AttrLst.Remove(this);
            if (ParentAttr != null)
                ParentAttr.EleLst.Remove(this);
        }

        //public static Dictionary<string, ProObAttr> TableToList(DataTable dt)
        //{

        //    Dictionary<string, ProObAttr> list = new Dictionary<string, ProObAttr>();
        //    if (dt == null) return list;
        //    ProObAttr m = null;
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        m = GetModelByDataRow(dr);
        //        if (!list.ContainsKey(m.ID))
        //            list.Add(m.ID, m);
        //    }
        //    return list;
        //}

        /// <summary>
        /// 数据行转对象
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        //public static ProObAttr GetModelByDataRow(DataRow dr)
        //{
        //    string lantype = PtlConsts.LanType == "cn" ? "" : PtlConsts.LanType; 
        //    ProObAttr m = new ProObAttr();
        //    m.ID = dr["ID"].ToString();
        //    m.PID = dr["PID"].ToString();
        //    m.OBIS = dr["OBIS"].ToString();
        //    m.ObjID = dr["ObjID"].ToString();
        //    m.attrmth = MyConvert.getInt32(dr["AttrMth"]);
        //    m.seq = dr["seq"].ToString();
        //    if (dr.Table.Columns.Contains("AmName"))                
        //       m.BaseProName = dr["AmName"].ToString();  
        //    else
        //       m.BaseProName = dr["ProName"].ToString();

        //    m.BaseUnits = dr["Units"].ToString();         
        //    m.BaseDisplay = dr["Display"].ToString();
        //    m.BaseDescs = dr["Descs"].ToString();
        //    try   //主要为导入导出加入try
        //    {
        //        if (dr.Table.Columns.Contains(lantype + "AmName"))
        //            m.ProName = dr[lantype + "AmName"].ToString();
        //        else
        //            m.ProName = dr[lantype + "ProName"].ToString();  //导出导入的文件里是proname
        //        m.Units = dr[lantype + "Units"].ToString();
        //        m.Display = dr[lantype + "Display"].ToString().Replace("\r", "").Replace("\n", "");   //分解描述                
        //        m.Descs = dr[lantype + "Descs"].ToString();
        //    }
        //    catch (Exception ex) { }

        //    if (string.IsNullOrEmpty(m.ProName))
        //        m.ProName = m.BaseProName;
        //    if (string.IsNullOrEmpty(m.Units))
        //        m.Units = m.BaseUnits;
        //    if (string.IsNullOrEmpty(m.Display))
        //        m.Display = m.BaseDisplay;
        //    if (string.IsNullOrEmpty(m.Descs))
        //        m.Descs = m.BaseDescs;           

         
        //    m.DataType = dr["DataType"].ToString();
        //    m.DataType = PubFunc62056.TransOldDatatype(m.DataType);

        //    m.DataLen = dr["DataLen"].ToString();
        //    if (string.IsNullOrEmpty(m.DataLen))
        //        m.DataLen = "0";
        //    m.DefValue = dr["DefValue"].ToString();
        //    if (!string.IsNullOrEmpty(dr["Scaler"].ToString()))
        //        m.Scaler = dr["Scaler"].ToString();
        //    //try  //多耗时达几秒
        //    //{
        //    //    m.Scaler = Int16.Parse(dr["Scaler"].ToString()).ToString();
        //    //}
        //    //catch
        //    //{ }
            
        //    m.accessMode = dr["RwFlag"].ToString();
        //    m.ShowFormat = dr["ShowFormat"].ToString(); //显示格式              
            
        //    m.parform = dr["ParForm"].ToString();  //参数窗口
        //    m.DataTypeDIY = dr["DataTypeDIY"].ToString();
        //    m.DataTypeDIY = PubFunc62056.TransOldDatatype(m.DataTypeDIY);

        //    if (dr.Table.Columns.Contains("SpeParForm"))  //特殊参数窗口名
        //        m.SpeParForm = dr["SpeParForm"].ToString();
        //    if (dr.Table.Columns.Contains("EleNodetype"))  //参数节点类型
        //        m.EleNodetype = (eleNodeType)(int.Parse(dr["EleNodetype"].ToString()));

        //    if (string.IsNullOrEmpty(m.ShowFormat))
        //    {   //如果没显示格式就给个默认的
        //        m.ShowFormat = PubFunc62056.GetFormatByFormType(m.DataType);

        //        if (string.IsNullOrEmpty(m.ShowFormat))  //如果还没显示格式就按自定义格式给个默认的
        //            m.ShowFormat = PubFunc62056.GetFormatByFormType(m.DataTypeDIY);
        //    }

        //    if ((m.RwFlag.Contains(TAttrAccess.Write.ToString())||
        //        m.RwFlag.Contains(TMthAccess.access.ToString())) &&
        //       m.parform == "0")
        //    {
        //        m.parform = PubFunc62056.GetParformByType(m.DataType);

        //        if (m.parform == "0" && !string.IsNullOrEmpty(m.DataTypeDIY))
        //            m.parform = PubFunc62056.GetParformByType(m.DataTypeDIY);
        //    }

        //    //显示数据类型的序号及字节长度
        //    if (!string.IsNullOrEmpty(m.DataType))
        //        m.DataTypeInfo = m.DataType + "(" + ((int)(enumData)Enum.Parse(typeof(enumData), m.DataType)).ToString() + "," +
        //                   ((int)(DataTypeLen)Enum.Parse(typeof(DataTypeLen), m.DataType)).ToString() + ")";

        //    string tmpstr = dr["IsVisible"].ToString().ToUpper();
        //    m.IsVisible = tmpstr == "TRUE" || tmpstr == "1";  //通过ProObAttrToDataSet转过来的DataSet里面的这个属性是boolean型的  值为ture或false
        //    //m.Availability = m.IsVisible;
        //    tmpstr = dr["IfParent"].ToString().ToUpper();
        //    m.IfParent = tmpstr == "TRUE" || tmpstr == "1";
        //    m.inputValue = m.DefValue;  //取默认值


        //    m.SendFunc = dr["SendFunc"].ToString();
        //    m.RecFunc = dr["RecFunc"].ToString();
        //    m.AnaFunc = dr["AnaFunc"].ToString();

        //    tmpstr = dr["IfInteroir"].ToString().ToUpper();
        //    m.IfInteroir = tmpstr == "TRUE" || tmpstr == "1";

        //    tmpstr = dr["IfReadPars"].ToString().ToUpper();
        //    m.IfReadPars = tmpstr == "TRUE" || tmpstr == "1";



        //    if (m.attrmth == (int)AttrType.方法 || m.attrmth == (int)AttrType.属性)
        //        m.ParLst = GetDefValueAttrPar(m.ID);  //取得推荐值参数项

        //    m.ModifiedBy = dr["ModifiedBy"].ToString();
        //    m.DateModified = dr["DateModified"].ToString();
        //    m.ICAttrMthID = dr["ICAttrMthID"].ToString();
        //   // m.CaptureObjLst = GetCaptureObjByAttr(m.ID);//这个时候属性列表还不全

        //    if (dr.Table.Columns.Contains("RoleAuth"))
        //    {   //hxh 2018-11-26
        //        m.roleAuth = dr["RoleAuth"].ToString();
        //        m.GetRoleAuthDic();
        //    }

        //    if (dr.Table.Columns.Contains("CAD"))  //hxh 2018-12-11 弹出界面导入导出时需要有
        //        m.CAD = dr["CAD"].ToString();

        //    //if (dr.Table.Columns.Contains("ObAttrMthID"))  //hxh  弹出界面导入导出时需要有
        //    //    m.ID = dr["ObAttrMthID"].ToString();

        //    if (dr.Table.Columns.Contains("RealValue"))  //shaunwang  2019-4-15 参数项的真实设置值
        //        m.RealValue = dr["RealValue"].ToString();
        //    return m;
        //}

        

        //hxh 取得各角色权限字典
        private void GetRoleAuthDic() {
            try
            {
                this.roleAuthDic.Clear();
                string[] RoleLst = this.roleAuth.Split(',');
                for (int i = 0; i < RoleLst.Length; i++)
                {
                    string[] strAuth = RoleLst[i].Split(':');
                    if (strAuth.Length == 2)
                        this.roleAuthDic.Add(strAuth[0], PubFunc62056.WordToAccessStr(strAuth[1], attrmth));
                }
            }
            catch { }
        }


        public List<ProObAttr> GetCaptureObjByAttr()
        {
            List<ProObAttr> ObjLst = new List<ProObAttr>();
            List<ProCaptureObj> Itemlst = ProCaptureObj.GetEleItemBySchID(ID);
            for (int i = 0; i < Itemlst.Count; i++) {
                bool find = false;
                //foreach (ProObAttr attr in Attrlst) 
                foreach (string id in Attrlst.Keys)
                {
                    ProObAttr attr = Attrlst[id];
                    if (Itemlst[i].RelateAttrID == attr.ID) {
                        ProObAttr Newattr = null;
                        if (string.IsNullOrEmpty(attr.SendFunc) && string.IsNullOrEmpty(attr.AnaFunc)) //没有发送前或解析后函数时复制
                        {
                            Newattr = attr.Copy();
                            Newattr.inputValue = "";  //把设置数据清空
                        }
                        else
                            Newattr = attr;//.Copy(); //hxh 捕捉对象不复制，取其本身，因涉及抄量纲需即时更新
                        if (Newattr.ProName.ToUpper() == ("value").ToUpper())
                            Newattr.ProName = attr.GetProObject().ObName + "-" + attr.ProName;
                       
                        ObjLst.Add(Newattr);
                        find = true;
                        break;
                    }
                }
                if (!find) {
                    ProObAttr probattr = new ProObAttr();
                    probattr.OBIS = probattr.ProName = Itemlst[i].RelateAttrID;
                    ObjLst.Add(probattr);
                }
            }
            CaptureObjLst = ObjLst;
            return ObjLst;
        }


        //获取数据库中所有属性
        public static Dictionary<string, ProObAttr> GetAllAttr()
        {
            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.TableName = "V_Obattrmth";

            //dtAll = PtlConsts.easyDb.Select();
            //Attrlst = ProObAttr.TableToList(dtAll);

            var list = vObAttrMthDbRepository.GetAllList().Result;
            foreach (var item in list)
            {
                var m = new ProObAttr();
                m.ID = item.ID;
                m.PID = item.PID;
                m.OBIS = item.OBIS;
                m.ObjID = item.ObjID;
                m.attrmth = MyConvert.getInt32(item.AttrMth);
                m.seq = item.seq.ToString();
                //if (dr.Table.Columns.Contains("AmName"))
                //    m.BaseProName = dr["AmName"].ToString();
                //else
                //    m.BaseProName = dr["ProName"].ToString();
                m.BaseProName = item.AmName;

                m.BaseUnits = item.Units ;
                m.BaseDisplay = item.Display;
                m.BaseDescs = item.Descs;
                //try   //主要为导入导出加入try
                //{
                //    if (dr.Table.Columns.Contains(lantype + "AmName"))
                //        m.ProName = dr[lantype + "AmName"].ToString();
                //    else
                //        m.ProName = dr[lantype + "ProName"].ToString();  //导出导入的文件里是proname
                //    m.Units = dr[lantype + "Units"].ToString();
                //    m.Display = dr[lantype + "Display"].ToString().Replace("\r", "").Replace("\n", "");   //分解描述                
                //    m.Descs = dr[lantype + "Descs"].ToString();
                //}
                //catch (Exception ex) { }

                if (string.IsNullOrEmpty(m.ProName))
                    m.ProName = m.BaseProName;
                if (string.IsNullOrEmpty(m.Units))
                    m.Units = m.BaseUnits;
                if (string.IsNullOrEmpty(m.Display))
                    m.Display = m.BaseDisplay;
                if (string.IsNullOrEmpty(m.Descs))
                    m.Descs = m.BaseDescs;


                m.DataType = item.DataType;
                m.DataType = PubFunc62056.TransOldDatatype(m.DataType);

                m.DataLen = item.DataLen.ToString();
                if (string.IsNullOrEmpty(m.DataLen))
                    m.DataLen = "0";
                m.DefValue = item.DefValue;
                //if (!string.IsNullOrEmpty(item.Scaler))
                    m.Scaler = item.Scaler.ToString();
                //try  //多耗时达几秒
                //{
                //    m.Scaler = Int16.Parse(dr["Scaler"].ToString()).ToString();
                //}
                //catch
                //{ }

                m.accessMode = item.RwFlag;
                m.ShowFormat = item.ShowFormat; //显示格式              

                m.parform = item.ParForm;  //参数窗口
                m.DataTypeDIY = item.DataTypeDIY;
                m.DataTypeDIY = PubFunc62056.TransOldDatatype(m.DataTypeDIY);

                //if (dr.Table.Columns.Contains("SpeParForm"))  //特殊参数窗口名
                //    m.SpeParForm = dr["SpeParForm"].ToString();
                //if (dr.Table.Columns.Contains("EleNodetype"))  //参数节点类型
                //    m.EleNodetype = (eleNodeType)(int.Parse(dr["EleNodetype"].ToString()));

                if (string.IsNullOrEmpty(m.ShowFormat))
                {   //如果没显示格式就给个默认的
                    m.ShowFormat = PubFunc62056.GetFormatByFormType(m.DataType);

                    if (string.IsNullOrEmpty(m.ShowFormat))  //如果还没显示格式就按自定义格式给个默认的
                        m.ShowFormat = PubFunc62056.GetFormatByFormType(m.DataTypeDIY);
                }

                if ((m.RwFlag.Contains(TAttrAccess.Write.ToString()) ||
                    m.RwFlag.Contains(TMthAccess.access.ToString())) &&
                   m.parform == "0")
                {
                    m.parform = PubFunc62056.GetParformByType(m.DataType);

                    if (m.parform == "0" && !string.IsNullOrEmpty(m.DataTypeDIY))
                        m.parform = PubFunc62056.GetParformByType(m.DataTypeDIY);
                }

                //显示数据类型的序号及字节长度
                if (!string.IsNullOrEmpty(m.DataType))
                    m.DataTypeInfo = m.DataType + "(" + ((int)(enumData)Enum.Parse(typeof(enumData), m.DataType)).ToString() + "," +
                               ((int)(DataTypeLen)Enum.Parse(typeof(DataTypeLen), m.DataType)).ToString() + ")";

                string tmpstr = item.IsVisible.ToString().ToUpper();
                m.IsVisible = tmpstr == "TRUE" || tmpstr == "1";  //通过ProObAttrToDataSet转过来的DataSet里面的这个属性是boolean型的  值为ture或false
                                                                  //m.Availability = m.IsVisible;
                tmpstr = item.IfParent.ToString();
                m.IfParent = tmpstr == "TRUE" || tmpstr == "1";
                m.inputValue = m.DefValue;  //取默认值


                m.SendFunc = item.SendFunc;
                m.RecFunc = item.RecFunc;
                m.AnaFunc = item.AnaFunc;

                tmpstr = item.IfInteroir.ToString().ToUpper();
                m.IfInteroir = tmpstr == "TRUE" || tmpstr == "1";

                tmpstr = item.IfReadPars.ToString().ToUpper();
                m.IfReadPars = tmpstr == "TRUE" || tmpstr == "1";



                if (m.attrmth == (int)AttrType.方法 || m.attrmth == (int)AttrType.属性)
                    //m.ParLst = GetDefValueAttrPar(m.ID);  //取得推荐值参数项

                m.ModifiedBy = item.ModifiedBy;
                m.DateModified = item.DateModified;
                m.ICAttrMthID = item.ICAttrMthID;
                // m.CaptureObjLst = GetCaptureObjByAttr(m.ID);//这个时候属性列表还不全

                //if (dr.Table.Columns.Contains("RoleAuth"))
                //{   //hxh 2018-11-26
                    m.roleAuth = item.RoleAuth;
                    m.GetRoleAuthDic();
                //}

                //if (dr.Table.Columns.Contains("CAD"))  //hxh 2018-12-11 弹出界面导入导出时需要有
                //    m.CAD = dr["CAD"].ToString(); 


                //if (dr.Table.Columns.Contains("RealValue"))  //shaunwang  2019-4-15 参数项的真实设置值
                //    m.RealValue = dr["RealValue"].ToString(); 

                if (!Attrlst.ContainsKey(m.ID))
                {
                    Attrlst.Add(m.ID, m);
                }
            }

            SetRelationship(Attrlst);
            return Attrlst;
        }

        /// <summary>
        /// 处理上下级关系
        /// </summary>
        /// <param name="alst"></param>
        private static void SetRelationship(Dictionary<string, ProObAttr> alst)
        {
            foreach (string id in alst.Keys)
            {
                ProObAttr findobj = alst[id];
                if (!string.IsNullOrEmpty(findobj.PID) && findobj.PID != "0")  //有父节点的
                {
                    if (alst.ContainsKey(findobj.PID))
                    {
                        alst[findobj.PID].AddSon(findobj);
                        findobj.ParentAttr = alst[findobj.PID];
                    }
                }
            }
        }

        /// <summary>
        /// 获取所有数据的集合
        /// </summary>
        /// <returns></returns>
        //public static DataTable GetAttrDataTable()
        //{
        //    if (dtAll == null)
        //        GetAllAttr();
        //    return dtAll;
        //}

        //根据ID查找属性
        //public static ProObAttr GetAttrByID(string id)
        //{
        //    if (dtAll == null)
        //        GetAllAttr();

        //    ProObAttr findObAttr = null;
        //    if (Attrlst.ContainsKey(id))
        //        findObAttr = Attrlst[id];

        //    //for (int i = 0; i < Attrlst.Count; i++)
        //    //{
        //    //    Application.DoEvents();
        //    //    if (Attrlst[i].ID == id)
        //    //    {
        //    //        findObAttr = Attrlst[i];
        //    //        GetEleByAttr(findObAttr);
        //    //        break;
        //    //    }
        //    //}

        //    return findObAttr;
        //}

        //根据OBIS获取属性
        public static ProObAttr GetAttrByCAD(string sCAD)
        {
            ProObAttr findObAttr = null;
            try
            {
                //for (int i = 0; i < Attrlst.Count; i++)
                foreach (string id in Attrlst.Keys)
                {
                    findObAttr = Attrlst[id].FindByCAD(sCAD, string.Empty);
                    if (findObAttr != null)
                        break;
                }
            }
            catch (Exception ex)
            {

            }
            return findObAttr;
        }


        //根据OBIS获取属性
        public static ProObAttr GetAttrByCAD(string sCAD, string attrtype)
        {
            ProObAttr findObAttr = null;

            //for (int i = 0; i < Attrlst.Count; i++)
            foreach (string id in Attrlst.Keys)
            {
                findObAttr = Attrlst[id].FindByCAD(sCAD, attrtype);
                if (findObAttr != null)
                    break;
            }

            return findObAttr;
        }
        

        //获取某个对象包含的属性
        public static List<ProObAttr> GetAttrByObject(ProObject inObject)
        {
            List<ProObAttr> list = new List<ProObAttr>();
            if (inObject.NodeType == ObjType.分类)
                return list;
            bool havefind = false;
            //for (int i = 0; i < Attrlst.Count; i++)
            foreach (string id in Attrlst.Keys)
            {
                if (Attrlst[id].PID != "0")
                    continue;
                if (havefind && Attrlst[id].OBIS != inObject.OBIS)  //
                    break;              
                if (Attrlst[id].ObjID == inObject.ID)
                {
                    havefind = true;
                    Attrlst[id].proObject = inObject;
                    //Attrlst[i].ClassID = inObject.ClassID;
                    Attrlst[id].CAD = inObject.proClass.ClassID + '.' + inObject.OBIS + '.' + Attrlst[id].seq + ".0";
                    
                    //GetEleByAttr(Attrlst[i]); //获取属性表中的元素                   

                    list.Add(Attrlst[id]);

                }
            }
            return list;
        }
    

        //获取某个属性包含的元素
        public static void GetEleByAttr(ProObAttr inAttr)
        {
            if (inAttr.EleLst == null)
                inAttr.EleLst = new List<ProObAttr>();
            else
                inAttr.EleLst.Clear();
            bool havefind = false;
            //for (int i = 0; i < Attrlst.Count; i++)
            foreach (string id in Attrlst.Keys)
            {
                if (havefind && Attrlst[id].PID != inAttr.ID) // 
                    break;

                if (Attrlst[id].PID == inAttr.ID)
                {
                    havefind = true;
                    Attrlst[id].ParentAttr = inAttr;
                    if (inAttr.proObject != null)// && inAttr.OBIS.Length >= 6)
                    {
                        if (Attrlst[id].AttrMth == AttrType.元素)
                        {
                            //Attrlst[i].ClassID = inAttr.proObject.ClassID;
                            Attrlst[id].CAD = inAttr.proObject.proClass.ClassID + '.' + inAttr.OBIS + '.' + inAttr.seq + '.' + Attrlst[id].seq;
                        }
                    }


                    //if (string.IsNullOrEmpty(Attrlst[i].OBIS))
                    //{
                    //    string aa = string.Empty;
                    //    int r = Attrlst[i].SaveObjectAttr(false, ref aa);
                    //    if (r <= 0)
                    //        MessageBox.Show(Attrlst[i].OBIS + "   :" + aa);
                    //}

                    GetEleByAttr(Attrlst[id]);
                   
                    inAttr.EleLst.Add(Attrlst[id]);
                  

                }
            }
        }

        /// <summary>
        /// 获取自身的OBIS，如果自身没有则获取父节点的OBIS
        /// </summary>
        /// <returns></returns>
        public string GetOBIS()
        {
            string rs = OBIS;
            if (!string.IsNullOrEmpty(rs))
                return rs;
            ProObAttr parAttr = this.ParentAttr;
            while (parAttr != null)
            {
                if (!string.IsNullOrEmpty(parAttr.OBIS))
                {
                    rs = parAttr.OBIS;
                    break;
                }
                else
                    parAttr = parAttr.ParentAttr;
            }
            return rs;
        }

        /// <summary>
        /// 获取自身的CAD，如果自身没有则获取父节点的CAD
        /// </summary>
        /// <returns></returns>
        public string GetCAD()
        {
            string rs = CAD;
            if (!string.IsNullOrEmpty(rs))
                return rs;
            ProObAttr parAttr = this.ParentAttr;
            while (parAttr != null)
            {
                if (!string.IsNullOrEmpty(parAttr.CAD))
                {
                    rs = parAttr.CAD;
                    break;
                }
                else
                    parAttr = parAttr.ParentAttr;
            }
            return rs;
        }


        ///// <summary>
        ///// 获取唯一标识码 OBIS+AttrType
        ///// </summary>
        ///// <returns></returns>
        //public string GetSerialNO()
        //{
        //    string sNO = CAD
        //               + (int)AttrMth
        //               + seq;
        //    ProObAttr parAttr = this.ParentAttr;
        //    while (parAttr != null)
        //    {
        //        sNO = parAttr.CAD
        //            + (int)parAttr.AttrMth
        //            + parAttr.seq
        //            + sNO;
        //        parAttr = parAttr.ParentAttr;
        //    }

        //    return sNO;
        //}

        /// <summary>
        /// 根据CAD查找自身及子节点是否与该CAD匹配
        /// </summary>
        /// <param name="OBIS"></param>
        /// attrtype指是属性还是方法
        /// <returns></returns>
        public ProObAttr FindByCAD(string sCAD, string attrtype) 
        {
            if (string.IsNullOrEmpty(sCAD)) return null;
            ProObAttr findObAttr = null;
            
            string appendname = string.Empty;
            string attrCAD = CAD ; //暂时
            if (attrCAD == sCAD)
            {
                if (string.IsNullOrEmpty(attrtype) || AttrMth.ToString() == attrtype)
                {
                    findObAttr = this.Copy();
                }
            }
            else
            {
                findObAttr = FindInElelst(this, sCAD, attrtype);
            }
            if (findObAttr != null)
            {               
                if (findObAttr.ParentAttr != null && findObAttr.ParentAttr.proObject != null)
                    appendname += findObAttr.ParentAttr.proObject.ObName;
                findObAttr.ProName = appendname + findObAttr.ProName;
            }
            return findObAttr;
        }

        /// <summary>
        /// 根据OBIS查找子节点是否与该OBIS匹配
        /// </summary>
        /// <param name="pAttr"></param>
        /// <param name="sOBIS"></param>
        /// <param name="attrtype"></param>
        /// <returns></returns>
        private ProObAttr FindInElelst(ProObAttr pAttr, string sCAD, string attrtype)
        {
            ProObAttr findObAttr = null;
            for (int i = 0; i < pAttr.EleLst.Count; i++)
            {
                if (pAttr.EleLst[i].CAD == sCAD)
                {
                    if (string.IsNullOrEmpty(attrtype) || pAttr.EleLst[i].AttrMth.ToString() == attrtype)
                    {
                        findObAttr = pAttr.EleLst[i].Copy();
                        break;
                    }
                }
                //else
                findObAttr = FindInElelst(pAttr.EleLst[i], sCAD, attrtype);
            }


            return findObAttr;
        }


        /// <summary>
        /// 清空输入值
        /// </summary>
        public void ClearInput()
        {
            this.inputValue = "";
            ClearSonInput(this);
        }

        /// <summary>
        /// 清空子节点输入值
        /// </summary>
        /// <param name="sonattr"></param>
        private void ClearSonInput(ProObAttr pattr)
        {
            for (int i = 0; i < pattr.EleLst.Count; i++)
            {
                pattr.EleLst[i].inputValue = "";
                ClearSonInput(pattr.EleLst[i]);
            }
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="sonattr"></param>
        public void AddSon(ProObAttr sonattr)
        {
            if (sonattr == null)
                return;
            EleLst.Add(sonattr);
            sonattr.ParentAttr = this;
            if (string.IsNullOrEmpty(sonattr.seq))
                sonattr.seq = (EleLst.Count - 1).ToString(); 
        }


        /// <summary>
        /// 移除子节点
        /// </summary>
        /// <param name="sonattr"></param>
        public void RemoveSon(ProObAttr sonattr)
        {
            if (sonattr == null)
                return;
            sonattr.ParentAttr = null;
            EleLst.Remove(sonattr);
        }

        /// <summary>
        /// 获取当前属性所属的Object
        /// </summary>
        /// <returns></returns>
        public ProObject GetProObject()
        {
            ProObject aobject = this.proObject;
            if (aobject == null)
            {
                ProObAttr parAttr = this.ParentAttr;  //父属性
                while (parAttr != null && aobject == null)
                {
                    aobject = parAttr.proObject;
                    parAttr = parAttr.ParentAttr;
                }
            }

            return aobject;
        }

        //复制自身
        public ProObAttr Copy()
        {
            return Copy(true);
        }


        /// <summary>
        /// 复制自身
        /// </summary>
        /// <param name="copyid">是否连ID也一起复制</param>
        /// <returns></returns>
        public ProObAttr Copy(bool copyid)
        {
            //新建一个
            ProObAttr newattr = new ProObAttr();

            //复制属性
            PropertyInfo[] fromFields = typeof(ProObAttr).GetProperties();
            try
            {
                PubFunction.SetProperties(fromFields, this, newattr);
            }
            catch (Exception ex)
            { 
            
            }

            if (!copyid)
                newattr.ID = string.Empty;
            //绑定树节点
            newattr.TreeNode = this.TreeNode;

            //绑定所属对象
            newattr.proObject = this.proObject;

            //复制属性包含的元素列表
            newattr.EleLst = new List<ProObAttr>();
            if (this.EleLst != null)
                for (int i = 0; i < this.EleLst.Count; i++)
                {
                    ProObAttr sonAttr = this.EleLst[i].Copy(copyid);
                    sonAttr.ParentAttr = newattr;
                    newattr.EleLst.Add(sonAttr);
                }

            //复制属性包含的参数列表
            newattr.ParLst = new List<ProObAttr>();
            if (this.ParLst != null)
                for (int i = 0; i < this.ParLst.Count; i++)
                {
                    ProObAttr sonAttr = this.ParLst[i].Copy(copyid);
                    sonAttr.ParentAttr = newattr;
                    newattr.ParLst.Add(sonAttr);
                }

            return newattr;
        }

        /// <summary>
        /// 复制其他对象的参数
        /// </summary>
        /// <param name="aObattr"></param>
        public void CopyPar(ProObAttr aObattr)
        {
            this.inputValue = aObattr.inputValue;
            if (aObattr.ParLst != null && aObattr.ParLst.Count > 0)
            {
                if (this.ParLst == null)
                    this.ParLst = new List<ProObAttr>();
                this.ParLst.Clear();

                for (int i = 0; i < aObattr.ParLst.Count; i++)
                {
                    ProObAttr sonAttr = aObattr.ParLst[i].Copy(false);
                    sonAttr.ParentAttr = this;
                    this.ParLst.Add(sonAttr);
                }
            }
            else
            {
                string[] parlst = this.inputValue.Split(new char[] { ',', ';' });
                for (int i = 0; i < this.EleLst.Count; i++)
                { 
                    if (parlst.Length > i)
                        this.EleLst[i].inputValue = parlst[i];
                }
            }
        }


        /// <summary>
        /// 设置各级节点的选中状态
        /// </summary>
        /// <param name="anode">当前操作的节点</param>
        /// <param name="ifcheck">是否选中</param>
        /// <param name="checkparent">是否更新父节点状态</param>
        public override void SetCheckStatus(bool acheck, bool checkparent)
        {
            SetCheckStatus(acheck, checkparent, true);
        }


        /// <summary>
        /// 设置各级节点的选中状态
        /// </summary>
        /// <param name="anode">当前操作的节点</param>
        /// <param name="ifcheck">是否选中</param>
        /// <param name="checkparent">是否更新父节点状态</param>
        public override void SetCheckStatus(bool acheck, bool checkparent, bool checkson)
        {
            if (acheck)
            {
                this.checkState = CheckState.Checked;
                if (this.proObject != null)
                    this.proObject.IfAttrChecked(checkson);

                //if (checkson)
                //{
                //    for (int i = 0; i < this.EleLst.Count; i++)
                //        this.EleLst[i].SetCheckStatus(true, false, checkson);
                //}

                if (checkparent)
                {
                    ProObAttr pnode = this.ParentAttr;
                    while (pnode != null)
                    {
                        pnode.checkState = CheckState.Checked;
                        if (pnode.proObject != null)
                            pnode.proObject.IfAttrChecked(checkson);
                        pnode = pnode.ParentAttr;
                    }
                }
            }
            else
            {
                this.checkState = CheckState.Unchecked;
                if (this.proObject != null)
                    this.proObject.IfAttrChecked(checkson);
                //if (checkson)
                //{
                //    for (int i = 0; i < this.EleLst.Count; i++)
                //        this.EleLst[i].SetCheckStatus(false, false, checkson);
                //}

                if (checkparent)
                {
                    ProObAttr pnode = this.ParentAttr;
                    while (pnode != null)
                    {
                        pnode.checkState = CheckState.Unchecked;

                        for (int j = 0; j < pnode.EleLst.Count; j++)
                        {
                            if (pnode.EleLst[j].checkState == CheckState.Checked)
                            {
                                pnode.checkState = CheckState.Checked;
                                break;
                            }
                        }

                        if (pnode.proObject != null)
                            pnode.proObject.IfAttrChecked(checkson);
                        pnode = pnode.ParentAttr;
                    }

                }
            }
        }



        /// <summary>
        /// 保存一个属性或方法
        /// </summary>
        /// <param name="insertFlag">true时是插入增加,false更新</param>
        /// <returns></returns>
        //public int SaveObjectAttr(bool insertFlag, ref string errinfo)
        //{
        //    PtlConsts.easyDb.Clear();
        //    PtlConsts.easyDb.TableName = ptltable;
        //    PtlConsts.easyDb.SetFieldValue("PID", PID, EasyDataType.String);

        //    ProObject aObject = this.GetProObject();
        //    if (aObject != null)
        //    {
        //        OBIS = aObject.OBIS;
        //        ObjID = aObject.ID;
        //    }

        //    PtlConsts.easyDb.SetFieldValue("OBIS", OBIS, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("ObjID", ObjID, EasyDataType.String); 
        //   // if (!string.IsNullOrEmpty(PtlConsts.LanType))
        //  //  {
        //    BaseProName = string.IsNullOrEmpty(BaseProName) ? ProName : BaseProName;
        //    PtlConsts.easyDb.SetFieldValue("AmName", BaseProName, EasyDataType.String);
        //    BaseUnits = string.IsNullOrEmpty(BaseUnits) ? Units : BaseUnits;
        //    PtlConsts.easyDb.SetFieldValue("Units", BaseUnits, EasyDataType.String);
        //    BaseDisplay = string.IsNullOrEmpty(BaseDisplay) ? Display : BaseDisplay;
        //    BaseDisplay = BaseDisplay.Replace("\r", "").Replace("\n", "");
        //    PtlConsts.easyDb.SetFieldValue("Display", BaseDisplay, EasyDataType.String);
        //    BaseDescs = string.IsNullOrEmpty(BaseDescs) ? Descs : BaseDescs;
        //    PtlConsts.easyDb.SetFieldValue("Descs", BaseDescs, EasyDataType.String);
        //   // }
        //    PtlConsts.easyDb.SetFieldValue("AttrMth", attrmth.ToString(), EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("seq", seq, EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("Scaler", Scaler, EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("DataType", DataType, EasyDataType.String);
        //    if (string.IsNullOrEmpty(DataLen))
        //        DataLen = "0";
        //    PtlConsts.easyDb.SetFieldValue("DataLen", DataLen, EasyDataType.Number);
        //   // PtlConsts.easyDb.SetFieldValue("RwFlag", RwFlag, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("RwFlag", accessMode, EasyDataType.String);  
        //    PtlConsts.easyDb.SetFieldValue("DefValue", DefValue, EasyDataType.String);

        //    PtlConsts.easyDb.SetFieldValue("ShowFormat", ShowFormat, EasyDataType.String);

        //    PtlConsts.easyDb.SetFieldValue("ParForm", parform, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("IsVisible", isvisible, EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("IfParent", ifparent, EasyDataType.Number);

        //    PtlConsts.easyDb.SetFieldValue("SendFunc", SendFunc, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("RecFunc", RecFunc, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("AnaFunc", AnaFunc, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("DataTypeDIY", DataTypeDIY, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("IfInteroir", ifInteroir, EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("IfReadPars", ifReadPars, EasyDataType.Number);
        //    PtlConsts.easyDb.SetFieldValue("ModifiedBy", ModifiedBy, EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("DateModified", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), EasyDataType.String);
        //    PtlConsts.easyDb.SetFieldValue("ICAttrMthID", ICAttrMthID, EasyDataType.String);
        //    int rs = 0;
        //    if (insertFlag)
        //    {
        //        ID = Guid.NewGuid().ToString();
        //        PtlConsts.easyDb.SetFieldValue("ID", ID, EasyDataType.String);
        //        rs = PtlConsts.easyDb.Insert(ref errinfo);
        //        if (rs > 0)
        //        {
        //            Attrlst.Add(this.ID, this);
        //            if (this.ParentAttr != null)
        //                this.ParentAttr.EleLst.Add(this);
        //            else
        //                if (this.proObject != null)
        //                    this.proObject.AttrLst.Add(this);
        //        }
        //    }
        //    else
        //    {
        //        PtlConsts.easyDb.SetWhereParameter(true, "ID", "=", ID, EasyDataType.String);
        //        rs = PtlConsts.easyDb.Update(ref errinfo);
        //    }

        //    if (rs >= 0)  //保存多语言
        //        rs = SaveAttrLang(PtlConsts.LanType, ref errinfo);

        //    return rs;
        //}

        /// <summary>
        /// 保存多语言信息
        /// </summary>
        /// <param name="errinfo"></param>
        /// <returns></returns>
        //public int SaveAttrLang(string lantype, ref string errinfo)
        //{ 
        //    int rs = 1;
        //    if (!string.IsNullOrEmpty(lantype) && lantype != "cn")
        //    {
        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable + "_Lang";
        //        ProName = string.IsNullOrEmpty(ProName) ? BaseProName : ProName;
        //        PtlConsts.easyDb.SetFieldValue(lantype + "AmName", ProName, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue(lantype + "Units", Units, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue(lantype + "Display", Display, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue(lantype + "Descs", Descs, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("ObAttrMthID", ID, EasyDataType.String);
        //        rs = PtlConsts.easyDb.Insert(ref errinfo);
        //        if (rs <= 0)
        //        {
        //            PtlConsts.easyDb.SetWhereParameter(true, "ObAttrMthID", "=", ID, EasyDataType.String);
        //            rs = PtlConsts.easyDb.Update(ref errinfo);
        //        }

        //    }
        //    return rs;
        //}


        /// <summary>
        /// 删除一个属性或方法
        /// </summary>
        /// <returns></returns>
        //public int DeleteObjectAttrByID(ref string errinfo)
        //{
        //    if (string.IsNullOrEmpty(ID)) 
        //        return 1;
        //    try
        //    {
        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable;
        //        PtlConsts.easyDb.SetWhereParameter(true, "ID", "=", ID, EasyDataType.String);
        //        int rs = PtlConsts.easyDb.Delete(ref errinfo);

        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable + "_Lang";
        //        PtlConsts.easyDb.SetWhereParameter(true, "ObAttrMthID", "=", ID, EasyDataType.String);
        //        rs = PtlConsts.easyDb.Delete(ref errinfo);

        //        if (rs >= 0)
        //        {
        //            for (int i = EleLst.Count - 1; i >= 0; i--)
        //                EleLst[i].DeleteObjectAttrByID(ref errinfo);  //删除该属性包含的属性或元素
        //            this.Dispose();
        //        }
        //        return rs;
        //    }
        //    catch(Exception ex)
        //    {
        //        errinfo = ex.Message;
        //        return -1;
        //    }
        //}

        #region 推荐值相关方法
        /// <summary>
        /// 获取推荐值参数列表
        /// </summary>
        /// <param name="attrid"></param>
        /// <param name="schid"></param>
        /// <returns></returns>
        //public static List<ProObAttr> GetDefValueAttrPar(string AttrID)
        //{
        //    if (DefValueParlst == null)
        //    {
        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.SetSQLText("select * from T_MtypeItemPar a left join V_obattrmth b on (a.ObAttrMthID=b.id) order by SNO");
        //        DefValueParlst = ProObAttr.TableToList(PtlConsts.easyDb.Select());
        //    }
        //    return GetDefValueSonPar(AttrID);
        //}


        private static List<ProObAttr> GetDefValueSonPar(string pid)
        {
            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.SetSQLText("select * from T_MtypeItemPar a left join V_obattrmth b on (a.ObAttrMthID=b.id) where  a.PID='" + pid + "' order by SNO");          
            //List<ProObAttr> parlst = ProObAttr.TableToList(PtlConsts.easyDb.Select());
            //for (int i = 0; i < parlst.Count; i++)
            //{
            //   // parlst[i].checkState = true;
            //    parlst[i].EleLst = GetDefValueSonPar(parlst[i].ID);
            //}
            List<ProObAttr> parlst = new List<ProObAttr>();
            //foreach (ProObAttr attr in  DefValueParlst)
            foreach (string id in DefValueParlst.Keys)
            {
                ProObAttr attr = DefValueParlst[id];
                if (attr.PID == pid)
                {
                    parlst.Add(attr);
                    attr.EleLst = GetDefValueSonPar(attr.ID);
                }
            }
            return parlst;
        }

        /// <summary>
        /// 获取参数列表
        /// </summary>
        /// <param name="schid">方案ID</param>
        /// <param name="pid">父对象唯一编码</param>
        /// <param name="parobattr">父对象</param>
        /// <param name="dt"></param>
        /// <returns></returns>
        //public static List<ProObAttr> GetSchemaSonPar(string schid, string pid, ProObAttr parobattr, DataTable dt)
        //{
        //    List<ProObAttr> parlst = new List<ProObAttr>();
        //    if (string.IsNullOrEmpty(pid) || dt == null)
        //        return parlst;
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        if (dr["BackUP1"].ToString() == schid && dr["PID"].ToString() == pid)
        //        {
        //            ProObAttr aObAttr = GetModelByDataRow(dr);
        //            aObAttr.checkState = aObAttr.IsVisible ? true : false;
        //            aObAttr.CanEdit = dr["CanEdit"].ToString() == "true";
        //            aObAttr.ParentAttr = parobattr;
        //            parlst.Add(aObAttr);
        //        }
        //    }

        //    for (int i = 0; i < parlst.Count; i++)
        //    {
        //        parlst[i].EleLst = GetSchemaSonPar(schid, parlst[i].ID, parlst[i], dt);
        //    }
        //    return parlst;
        //}  
       

      
       #endregion

        /// <summary>
        /// 初始化传入值，比如传入[系统时间]需要取当前时间
        /// </summary>
        private void PreparePar()
        {
            string rs = inputValue;
            try
            {
                switch (ParForm)
                {
                    case TFormType.日期时间带周次毫秒:                  
                    case TFormType.日期带周次:
                    case TFormType.时间:
                        if (rs.IndexOf("[") >= 0 && rs.IndexOf("]") > 0)
                        {
                            DateTime idatetime = DateTime.Now;
                            rs = idatetime.ToString("yyyy-MM-dd HH:mm:ss");
                            if (!string.IsNullOrEmpty(ShowFormat))
                            {
                                rs = ShowFormat;
                                rs = rs.Replace("yyyy", idatetime.Year.ToString());
                                rs = rs.Replace("MM", idatetime.Month.ToString().PadLeft(2, '0'));
                                rs = rs.Replace("dd", idatetime.Day.ToString().PadLeft(2, '0'));

                                int ww = (int)idatetime.DayOfWeek;  //hxh 62056里的星期是从1－7
                                if (ww == 0) ww = 7;
                                rs = rs.Replace("ww", ww.ToString().PadLeft(2, '0'));
                                
                                rs = rs.Replace("HH", idatetime.Hour.ToString().PadLeft(2, '0'));
                                rs = rs.Replace("mm", idatetime.Minute.ToString().PadLeft(2, '0'));
                                rs = rs.Replace("ss", idatetime.Second.ToString().PadLeft(2, '0'));
                                rs = rs.Replace("hs", "00");//not specified
                                rs = rs.Replace("nnnn", "8000");//not specified
                                rs = rs.Replace("st", "00");//not specified

                            }
                        }

                        break;
                }

                if (DataTypeDIY == enumData.time.ToString())
                {
                    rs = DateTime.Parse(inputValue).ToString("HH:mm:ss 00");
                }
            }
            catch
            { }
            inputValue = rs;

        }

        /// <summary>
        /// 将界面输入值转为十六进制数 
        /// </summary>
        /// <param name="datanode"></param>
        /// <returns></returns>
        public string InputToFrame()
        {
            PreparePar();
            return DisplayToFrame(inputValue);
        }


        /// <summary>
        /// 抄读值转为界面显示值 
        /// </summary>
        /// <param name="datanode"></param>
        /// <returns></returns>
        public string FrameToInput()
        {
            return FrameToDisplay(readValue);            
        }

        /// <summary>
        /// 获取所有子节点的输入值拼起来，逗号隔开
        /// </summary>
        public void GetAllChildValue()
        {
            if ( EleLst == null || EleLst.Count == 0)//DataType == enumData.CSD.ToString() ||
                return;
            string allvalue = string.Empty;
            for (int i = 0; i < EleLst.Count; i++)
            {
                if (DataType == enumData.bit_string.ToString() || DataType.Contains(enumData.unsigned.ToString()) 
                    || DataType == enumData.Enum.ToString())
                {
                    allvalue += string.IsNullOrEmpty(EleLst[i].inputValue) ? "0" : EleLst[i].InputToFrame();                    
                              
                }
                else
                {
                    if (string.IsNullOrEmpty(EleLst[i].inputValue))
                        continue;
                    allvalue += EleLst[i].inputValue
                              + ",";
                }
            }
            
            if (allvalue.Length > 0 && allvalue.Substring(allvalue.Length - 1, 1) == ",")
                allvalue = allvalue.Substring(0, allvalue.Length - 1);

            if (DataType == enumData.bit_string.ToString()) //hxh 2019-6-19 bitstring 是右边补齐
            {
                try
                {
                    int Dlen = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(DataLen) / 8));
                    allvalue = allvalue.PadRight(Dlen * 8, '0');
                    allvalue = MyConvert.BinToHex(allvalue).PadLeft(Dlen * 2, '0');
                }
                catch
                { }
            }
            if (DataType.Contains(enumData.unsigned.ToString()))
            {
                allvalue = MyConvert.BinToHex(allvalue);
                try
                {
                    allvalue = allvalue.PadLeft(Int16.Parse(DataLen) * 2, '0');
                }
                catch
                { }
            }

            //if (DataType.Contains(enumData.unsigned.ToString()) || DataType == enumData.bit_string.ToString())
            //{
            //    allvalue = MyConvert.BinToHex(allvalue);
            //    if (!string.IsNullOrEmpty(DataLen) && DataLen != "0")
            //        allvalue = allvalue.PadLeft(int.Parse(DataLen) * 2, '0');
            //}
            if (DataType == enumData.Enum.ToString())
                allvalue = MyConvert.BinToHex(allvalue,true);           
            //if (DataType == enumData.bstring.ToString())
            //    allvalue = MyConvert.BinToHex(allvalue, int.Parse(DataLen));
           

            this.inputValue = allvalue;
        }

        /// <summary>
        /// 判断输入值是否为空
        /// </summary>
        public bool IfEmptyInputValue()
        {
            bool isEmpty = string.IsNullOrEmpty(this.inputValue);

            if (!isEmpty || EleLst == null || EleLst.Count == 0)
                return isEmpty;
            
            for (int i = 0; i < EleLst.Count; i++)
            {
                isEmpty = EleLst[i].IfEmptyInputValue();
                if (!isEmpty)
                    break;
            }
            return isEmpty;
        }

        //hxh 2019-5-30 加入抄读数据清空
        public void ClearReadValue() {
            try
            {
                this.readValue = string.Empty;
                
                for (int i = 0; i < this.EleLst.Count; i++)
                {
                    this.EleLst[i].ClearReadValue();
                }
                this.ReadParLst.Clear();
                //for (int i = 0; i < this.ReadParLst.Count; i++)
                //{
                //    this.ReadParLst[i].ClearReadValue();
                //}
            }
            catch { }
        }

        /// <summary>
        /// 将传入值分到子节点去，用于直接通过OAD取到对象，之后直接赋值，比如脚本中
        /// </summary>
        public int SplitValueWhenNeed(ref string errinfo)
        {
            int rs = 0;
            if (string.IsNullOrEmpty(inputValue))
                return rs;
            string[] parlst;
            int index = 0;
            if (DataType == enumData.array.ToString() || DataType == enumData.structure.ToString())
            {
                if (this.ParLst != null && this.ParLst.Count > 0)
                    return rs;
                parlst = inputValue.Replace("{", "").Replace("}", "").Split(',');

                ValueToSon(this.EleLst, parlst, ref index);
            }
            else
                if ((DataType == enumData.bit_string.ToString() || DataType.Contains(enumData.unsigned.ToString())
                    || DataType == enumData.Enum.ToString()) && string.IsNullOrEmpty(Display))  //按二进制拆解
                {
                    try
                    {
                        int Dlen = Int16.Parse(this.DataLen);
                        parlst = inputValue.Replace("{", "").Replace("}", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (parlst.Length == 1)  //传入值为十六进制参数
                        {
                            string bitstring = MyConvert.HexToBin(inputValue).PadLeft(Dlen * 8, '0');

                            for (int i = 0; i < this.EleLst.Count; i++)
                            {
                                int bitlen = Convert.ToInt32(this.EleLst[i].DataLen); //取位的个数
                                if (bitlen == 0)
                                    bitlen = 1;
                                string value = bitstring.Substring(0, bitlen);
                                this.EleLst[i].inputValue = PtlCommunal.Explaindata2(value, this.EleLst[i].Display); 
                                this.EleLst[i].checkState = CheckState.Checked;
                                
                                bitstring = bitstring.Remove(0, bitlen);
                            }
                        }
                        else //传入值为各子节点参数
                            if (parlst.Length > 1)
                            {
                                ValueToSon(this.EleLst, parlst, ref index);
                            }
                    }
                    catch (Exception ex)
                    {
                        rs = -1;
                        errinfo = "input parameter error:" + inputValue;
                    }
                }
            rs = 1;
            return rs;
        }

        /// <summary>
        /// 参数值拆分到子节点
        /// </summary>
        /// <param name="sonlst"></param>
        /// <param name="parlst"></param>
        /// <param name="index"></param>
        private void ValueToSon(List<ProObAttr> sonlst, string[] parlst, ref int index)
        {
            string errinfo = string.Empty;
            for (int i = 0; i < sonlst.Count; i++)
            {
                sonlst[i].checkState = index < parlst.Length ? CheckState.Checked : CheckState.Unchecked;

                if (sonlst[i].DataType == enumData.array.ToString() || sonlst[i].DataType == enumData.structure.ToString())
                {
                    sonlst[i].inputValue = "0"; //随便给个值，便于底层处理  
                    if (index < parlst.Length)
                        ValueToSon(sonlst[i].EleLst, parlst, ref index);
                }
                else
                {
                    if (index < parlst.Length)
                    {
                        string[] par = parlst[index].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (par.Length > 1)
                            sonlst[i].inputValue = par[1];
                        else
                            sonlst[i].inputValue = par[0];
                        sonlst[i].SplitValueWhenNeed(ref errinfo);
                        index++;
                    }
                }
            }

        }


        #region 根据OBIS或名称深度查找属性
        //根据OAD或属性名称获取属性,返回搜到的属性在属性列表中的位置
        public static ProObAttr GetAttrByOBISorName(string sOADorName, ref int iIndex)
        {
            return GetAttrByOBISorName(sOADorName, "", "", ref iIndex);
        }

        //根据OBIS或属性名称获取属性,返回搜到的属性在属性列表中的位置
        public static ProObAttr GetAttrByOBISorName(string sOBISorName, string attrtype, string attrid, ref int iIndex)
        {
            ProObAttr findObAttr = null;

            //for (int i = iIndex; i < Attrlst.Count; i++)
            foreach (string id in Attrlst.Keys)
            {
                findObAttr = Attrlst[id].FindByOBISorName(sOBISorName, attrtype, attrid);
                if (findObAttr != null)
                {
                    //iIndex = i;
                    break;
                }
            }
            return findObAttr;
        }

        /// <summary>
        /// 根据OBIS或属性名称查找属性节点
        /// </summary>
        /// <param name="OBIS"></param>
        /// <returns></returns>
        public ProObAttr FindByOBISorName(string sOBISorName, string attrtype, string attrid)
        {
            if (string.IsNullOrEmpty(sOBISorName)) 
                return null;
            ProObAttr findObAttr = null;
            if ((sOBISorName == this.OBIS || this.ProName.ToUpper().Contains(sOBISorName)) 
                && (string.IsNullOrEmpty(attrtype) || attrtype.Contains(this.AttrMth.ToString()))
                && (string.IsNullOrEmpty(attrid) || this.seq == attrid))
            {
                findObAttr = this;                
            }
            else
            {
                findObAttr = FindInElelstByOBISorName(this, sOBISorName, attrtype, attrid);
            }            
            return findObAttr;
        }

        /// <summary>
        /// 根据OBIS或属性名称查找子节点
        /// </summary>
        /// <param name="pAttr"></param>
        /// <param name="sOBIS"></param>
        /// <param name="attrtype"></param>
        /// <returns></returns>
        private ProObAttr FindInElelstByOBISorName(ProObAttr pAttr, string sOBISorName, string attrtype, string attrid)
        {
            ProObAttr findObAttr = null;
            for (int i = 0; i < pAttr.EleLst.Count; i++)
            {
                if ((sOBISorName == pAttr.EleLst[i].OBIS || pAttr.EleLst[i].ProName.Contains(sOBISorName)) 
                    && (string.IsNullOrEmpty(attrtype) || attrtype.Contains(pAttr.EleLst[i].AttrMth.ToString()))
                    && (string.IsNullOrEmpty(attrid) || pAttr.EleLst[i].seq == attrid))
                {                   
                    findObAttr = pAttr.EleLst[i];
                    break;                                      
                }
                findObAttr = FindInElelstByOBISorName(pAttr.EleLst[i], sOBISorName, attrtype, attrid);
            }
            return findObAttr;
        }
        #endregion

        /// <summary>
        /// 数据对象转为DataSet后再转为xml字符串
        /// </summary>
        /// <returns></returns>
        //public static string ProObAttrToStr(List<ProObAttr> list, ref string errinfo)
        //{            
        //    DataSet ds = ProObAttrToDataSet(list) ;
        //    string rs = RWOutFiles.DataSetToXMlStr(ds, ref errinfo);
        //    return rs;
        //}

        //public static DataSet ProObAttrToDataSet(List<ProObAttr> list)
        //{  
        //    DataTable dtpro = new DataTable();  //数据项数据集
        //    Type type = typeof(ProObAttr);
        //    PropertyInfo[] pArray = type.GetProperties(); //集合属性数组  
        //    foreach (PropertyInfo p in pArray)
        //    {
        //        if (FieldLst.IndexOf(p.Name) >= 0)
        //            continue;
        //        if (!dtpro.Columns.Contains(p.Name))
        //            dtpro.Columns.Add(p.Name, p.PropertyType); //添加列名及对应类型 
        //    }

        //    DataTable dtpropar = new DataTable();  //数据项参数数据集
        //    foreach (PropertyInfo p in pArray)
        //    {
        //        if (FieldLst.IndexOf(p.Name) >= 0)
        //            continue;
        //        if (!dtpropar.Columns.Contains(p.Name))
        //            dtpropar.Columns.Add(p.Name, p.PropertyType); //添加列名及对应类型 
        //    }

        //    ListToTable(list, dtpro, dtpropar);

        //    DataSet dsProObAttr = new DataSet();
        //    dsProObAttr.Tables.Add(dtpro.Copy());
        //    dsProObAttr.Tables.Add(dtpropar.Copy());

        //    return dsProObAttr;
        //}

        /// <summary>  
        /// List集合转DataTable  
        /// </summary>  
        /// <param name="list">传入集合</param>  
        /// <returns>返回datatable结果</returns>  
        //public static void ListToTable(List<ProObAttr> list, DataTable dtpro, DataTable dtpropar)
        //{
        //    Type type = typeof(ProObAttr);
        //    PropertyInfo[] pArray = type.GetProperties(); //集合属性数组  
        //    foreach (ProObAttr item in list)
        //    {
        //        DataRow dr = dtpro.NewRow();
        //        foreach (PropertyInfo p in pArray)
        //        {
        //            try
        //            {
        //                if (FieldLst.IndexOf(p.Name) >= 0)
        //                    continue;
        //                object obj = p.GetValue(item, null);
        //                if (obj == null)
        //                    obj = string.Empty;

        //                dr[p.Name] = obj;
        //            }
        //            catch
        //            { }
        //        }
        //        dtpro.Rows.Add(dr);

        //        //导入方案项参数
        //        ParListToTable(item.ParLst, item.BackUP1, item.ID, dtpropar);

        //    }

        //}



        /// <summary>  
        /// List集合转DataTable  
        /// </summary>  
        /// <param name="list">传入集合</param>  
        /// <returns>返回datatable结果</returns>  
        //public static void ParListToTable(List<ProObAttr> list, string schid, string pid, DataTable dtitempar)
        //{
        //    Type type = typeof(ProObAttr);
        //    PropertyInfo[] pArray = type.GetProperties(); //集合属性数组  
        //    foreach (ProObAttr item in list)
        //    {
        //        item.PID = pid;
        //        item.BackUP1 = schid;
        //        item.BackUP2 = Guid.NewGuid().ToString(); //相当于方案项参数里的ID,子节点的父ID由此来
        //        if (string.IsNullOrEmpty(item.ID))
        //            item.ID = Guid.NewGuid().ToString();
        //        item.DefValue = item.inputValue;

        //        DataRow dr = dtitempar.NewRow();
        //        foreach (PropertyInfo p in pArray)
        //        {
        //            try
        //            {
        //                if (FieldLst.IndexOf(p.Name) >= 0)
        //                    continue;
        //                object obj = p.GetValue(item, null);
        //                if (obj == null)
        //                    obj = string.Empty;

        //                dr[p.Name] = obj;
        //            }
        //            catch
        //            { }
        //        }
        //        dtitempar.Rows.Add(dr);
        //        if (item.ParLst.Count == 0)
        //            ParListToTable(item.EleLst, schid, item.BackUP2, dtitempar);
        //        else
        //            ParListToTable(item.ParLst, schid, item.BackUP2, dtitempar);
        //    }

        //}



        /// <summary>
        /// 从xml字符串转为对象集合
        /// </summary>
        /// <returns></returns>
        //public static List<ProObAttr> StrToProObAttr(string xmlstr, ref string errinfo)
        //{
        //    List<ProObAttr> list = new List<ProObAttr>();
        //    if (string.IsNullOrEmpty(xmlstr))
        //        return list;

        //    if (xmlstr.Contains("<NewDataSet>"))
        //        xmlstr = "<?xml version=\"1.0\" standalone=\"yes\"?>"
        //                + xmlstr.Substring(xmlstr.IndexOf("<NewDataSet>"));

        //    DataSet dsProObAttr = RWOutFiles.XmlStrToDataSet(xmlstr, ref errinfo);
        //    return DataSetToProObAttr(dsProObAttr, ref errinfo);
        //}


        /// <summary>
        /// DataSet转为数据项对象
        /// </summary>
        /// <returns></returns>
        //public static List<ProObAttr> DataSetToProObAttr(DataSet dsProObAttr, ref string errinfo)
        //{
        //    List<ProObAttr> list = new List<ProObAttr>();
        //    if (dsProObAttr == null || !string.IsNullOrEmpty(errinfo))
        //        return list;


        //    DataTable dtpro = dsProObAttr.Tables[0];  //数据项数据集 
        //    DataTable dtpropar = null;
        //    if (dsProObAttr.Tables.Count > 1)
        //        dtpropar = dsProObAttr.Tables[1];  //数据项参数数据集
        //    foreach (DataRow dr in dtpro.Rows)
        //    {
        //        ProObAttr aObAttr = GetModelByDataRow(dr);
        //        aObAttr.checkState = aObAttr.Availability ? true : false;
        //        aObAttr.inputValue = dr["inputValue"].ToString();
        //        aObAttr.CanEdit = dr["CanEdit"].ToString() == "true";
        //        aObAttr.BackUP1 = dr["BackUP1"].ToString();                
        //        aObAttr.ParLst = GetSchemaSonPar(aObAttr.BackUP1, dr["ID"].ToString(), aObAttr, dtpropar);
        //        list.Add(aObAttr);
        //    }


        //    return list;
        //}

        /// <summary>
        /// 获取参数列表
        /// </summary>
        /// <param name="schid">方案ID</param>
        /// <param name="pid">父对象唯一编码</param>
        /// <param name="parobattr">父对象</param>
        /// <param name="dt"></param>
        /// <returns></returns>
        //public static List<ProObAttr> GetSchemaSonPar(string schid, string pid, ProObAttr parobattr, DataTable dt)
        //{
        //    List<ProObAttr> parlst = new List<ProObAttr>();
        //    if (string.IsNullOrEmpty(pid) || dt == null)
        //        return parlst;
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        if (dr["BackUP1"].ToString() == schid && dr["PID"].ToString() == pid)
        //        {
        //            ProObAttr aObAttr = GetModelByDataRow(dr);
        //            aObAttr.checkState = aObAttr.Availability ? true : false;
        //            aObAttr.CanEdit = dr["CanEdit"].ToString() == "true";
        //            aObAttr.BackUP2 = dr["BackUP2"].ToString();
        //            aObAttr.ParentAttr = parobattr;
        //            parlst.Add(aObAttr);
        //        }
        //    }

        //    for (int i = 0; i < parlst.Count; i++)
        //    {
        //        parlst[i].EleLst = GetSchemaSonPar(schid, parlst[i].BackUP2, parlst[i], dt);
        //    }
        //    return parlst;
        //}

        //更新属性的换算和单位
        //public static int UpdateSalerUnit(string AttrId, string Scaler, string units)
        //{
        //    string errinfo = string.Empty;
        //    try
        //    {
                
        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable;
        //        PtlConsts.easyDb.SetFieldValue("Scaler", Scaler, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("Units", units, EasyDataType.String);
        //        PtlConsts.easyDb.SetWhereParameter(true, "ID", "=", AttrId, EasyDataType.String);
        //        int rs = PtlConsts.easyDb.Update(ref errinfo);                
        //        return rs;
        //    }
        //    catch (Exception ex)
        //    {
        //        errinfo = ex.Message;
        //        return -1;
        //    }

        //}


        //更新属性的数据类型
        //public static int UpdateDataType(string AttrId, string datatype)
        //{
        //    string errinfo = string.Empty;
        //    try
        //    {

        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable;
        //        PtlConsts.easyDb.SetFieldValue("DataType", datatype, EasyDataType.String);
        //        PtlConsts.easyDb.SetWhereParameter(true, "ID", "=", AttrId, EasyDataType.String);
        //        int rs = PtlConsts.easyDb.Update(ref errinfo);
        //        return rs;
        //    }
        //    catch (Exception ex)
        //    {
        //        errinfo = ex.Message;
        //        return -1;
        //    }

        //}

        //根据接口类属性信息更新对象中的相应属性信息
        //public static int UpdateObAttrByClass(ProICAttrMth ICAttr,ref string errinfo) 
        //{ 
        //    try
        //    {
        //        errinfo = string.Empty;
        //        string classid = ICAttr.proClass.ClassID;
        //        int mth = (int)ICAttr.AttrMth;
        //        int seq = ICAttr.Seq;     
        //        PtlConsts.easyDb.Clear();
        //        PtlConsts.easyDb.TableName = ptltable;
        //       // PtlConsts.easyDb.SetFieldValue("AmName", ICAttr.ProName, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("AttrMth", ((int)ICAttr.AttrMth).ToString(), EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("Seq", ICAttr.Seq.ToString(), EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("Scaler", ICAttr.Scaler, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("Units", ICAttr.Units, EasyDataType.String);
        //        if (ICAttr.DataType != enumData.Data.ToString())
        //           PtlConsts.easyDb.SetFieldValue("DataType", ICAttr.DataType, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("DataLen", ICAttr.DataLen, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("RwFlag", ICAttr.accessMode, EasyDataType.String);              
        //        PtlConsts.easyDb.SetFieldValue("ShowFormat", ICAttr.ShowFormat, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("ParForm", ((int)ICAttr.ParForm).ToString(), EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("IsVisible", ICAttr.IsVisible ? "1" : "0", EasyDataType.String);           
        //        PtlConsts.easyDb.SetFieldValue("SendFunc", ICAttr.SendFunc, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("RecFunc", ICAttr.RecFunc, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("AnaFunc", ICAttr.AnaFunc, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("DataTypeDIY", ICAttr.DataTypeDIY, EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("IfInteroir", ICAttr.IfInteroir ? "1" : "0", EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("IfReadPars", ICAttr.IfReadPars ? "1" : "0", EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("Display", ICAttr.Display , EasyDataType.String);
        //        PtlConsts.easyDb.SetFieldValue("ModifiedBy", ICAttr.ModifiedBy, EasyDataType.String);

        //        PtlConsts.easyDb.SetFieldValue("DateModified", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), EasyDataType.String);
        //        //string IDs = "(select b.id from t_objects a,t_obattrmth b where a.classid="
        //        //    + classid + " and a.ID=b.objid and b.attrmth=" + mth + " and b.seq=" + seq + ")";

        //        //PtlConsts.easyDb.SetWhereParameter(true, "ID", "in", IDs, EasyDataType.Number);
        //        PtlConsts.easyDb.SetWhereParameter(true, "ICAttrMthID", "=", ICAttr.ID, EasyDataType.String);
        //        int rs = PtlConsts.easyDb.Update(ref errinfo);
        //        return rs;
        //    }
        //    catch (Exception ex)
        //    {
        //        errinfo = ex.Message;
        //        return -1;
        //    }

        //}

    }

}
